package com.rg.service;

import com.rg.dao.Orderdao;
import com.rg.model.OrderItemsModel;
import com.rg.model.OrderModel;
import com.rg.utils.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

//服务用于保存订单和订单项到数据库。
public class OrderService {
    private Orderdao orderdao= new Orderdao();
    public void saveOrder(OrderModel order){
        Connection conn=null;
        try {
            conn= DruidUtils.getConnection();
            conn.setAutoCommit(false);
            orderdao.insertOrder(conn,order);
            for (OrderItemsModel item: order.getListmap().values()){
                orderdao.insertOrderItems(conn,item);}
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            if (conn!=null){
                try{conn.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
    public void addOrder(OrderModel order) {
        Connection con = null;
        try {
            con = DruidUtils.getConnection();
            con.setAutoCommit(false);
            orderdao.insertOrder(con, order);
            int id = orderdao.getLastInsertId(con);
            order.setId(id);
            for(OrderItemsModel item : order.getListmap().values()) {
                orderdao.insertOrderItems(con, item);
            }

            con.commit();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            if(con!=null)
                try {
                    con.rollback();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
        }
    }
    public List<OrderModel> selectAll(int userid){
        List<OrderModel> list=null;
        try {
            list = orderdao.selectAll(userid);
            for(OrderModel o :list) {
                List<OrderItemsModel> l = orderdao.selectAllItem(o.getId());
                o.setOrderitem(l);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
}